package com.by.service.imlp;

import com.by.bean.Permission;
import com.by.bean.User;
import com.by.common.utils.JwtTokenUtil;
import com.by.dao.UserDao;
import com.by.service.UserService;
import com.by.vo.LoginParams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.util.List;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    UserDao userDao;
    @Autowired
    JwtTokenUtil jwtTokenUtil;
    @Autowired
    PasswordEncoder passwordEncoder;

    @Override
    public User getUserByName(String name) {
        List<User> users= userDao.getUserByName(name);
        Assert.isTrue(users.size()==1,"您输入的账户不存在，或者有多个相同的账户");
        return users.get(0);
    }

    @Override
    public List<Permission> getPermissionsByUserId(Integer id) {
        return userDao.getPermisionByUserId(id);
    }

    @Override
    public String login(LoginParams loginParams) {
        String username = loginParams.getName();
        Assert.hasText(username,"账号必须不能为空");
        String password = loginParams.getPassword();
        Assert.hasText(password,"密码必须不能为空");
        User userByName = getUserByName(username);
        boolean matches = passwordEncoder.matches(password, userByName.getPassword());
        if(matches){
            return jwtTokenUtil.generateToken(userByName);
        }
        return null;
    }
}